<template>
    <!-- <div class="page-wrap"> -->
        <MenuPage 
            ref="selectTable"
            :data="ExperimentalUserGroupList" 
            :columns="groupCol"
            :loading="experGroupLoading"
            :page.sync="groupPage"
            :size.sync="groupPageSize"
            :total="expGroupCount"
            showSelectTag
            :selectName="(group) => {
                return `${group.name}${ isCanClick(group.creator) ? '-无删除权限' : '' }`
            }"
            :selection.sync="selectGroups" 
            @queryFun="queryExperimentalUserGroup">
        <template slot="search">
            <Button ghost style="height: 32px" type="primary" icon="ios-cloud-upload-outline" 
                    v-if="distributed" @click="reportedGroups">实验组上报</Button>
            <Button ghost style="height: 32px;margin-left: 15px" type="primary" icon="ios-cloud-download-outline" @click="exportGroups">导出实验组</Button>
            <Tooltip max-width="200" content="导入实验组会忽略重名的数据">
                <Upload ref="upload"
                        :action="uploadGroupAction"
                        :show-upload-list="false"
                        :format="['xlsx']"
                        :on-format-error="handleFormatError"
                        :on-success="getImageUrl"
                        :on-progress="handleProgress"
                        :before-upload="handleBeforeUpload"
                        :headers="uploadHeader">
                    <Button ghost style="height: 32px;" type="primary" :disabled="uploadList.length > 0">
                        <div v-if="uploadList.length == 0">
                            <Icon type="ios-cloud-upload-outline"></Icon>
                            <span>导入实验组</span>
                        </div>
                        <div class="demo-upload-list" v-for="item in uploadList">
                            <Progress v-if="item.showProgress" :percent="item.percentage" hide-info style="width:100px"></Progress>
                        </div>
                    </Button>
                </Upload>
            </Tooltip>
            <Button v-if="selectGroups.length == 0&&mainRangeflag" ghost style="height: 32px;margin-left: 15px" type="error" @click="isDdeleteGroups">批量删除</Button>
            <Poptip
            v-if="selectGroups.length != 0"
                confirm
                title="确定删除实验组?"
                @on-ok="deleteGroups"
                @on-cancel="">
                <Button ghost style="height: 32px;" type="error" v-if="selectGroups.length != 0&&mainRangeflag">批量删除</Button>
            </Poptip>
            <Button ghost style="height: 32px;" type="primary" icon="ios-download-outline"><a href="static/experimental_group_template.xlsx" download="experimental_group_template.xlsx" class="downloadUrl">下载导入实验组模板</a></Button>
            <Button ghost style="height: 32px;" type="primary" class="md-add-jh" @click="creatGroupBtn">创建实验组</Button>
            <div style="height: 32px;line-height: 32px;">
                <Checkbox v-model="createByMe" @on-change="searchCreatedByMe" style="width: 66px;">由我创建
                </Checkbox>
            </div>
            <Select filterable @on-change="searchItem" v-model="rangeId" style="width:150px;margin-left:15px" placeholder="所属靶场" clearable v-if="distributedRange && $store.state.common.showDistributed">
                <Option v-for='(items,index) in rangeAllList' :value="items.id" :key="index+'range'">{{items.name}}</Option>
            </Select>
            <i-select clearable v-model="filterExpGroup" placeholder="可见范围" style="width: 150px;margin-left: 15px" @on-change="changeExpGroupState">
                <Option value="company">单位</Option>
                <Option value="person">个人</Option>
            </i-select>
            <Input v-model.trim="searchExpGroupInput" placeholder="实验组名称" clearable @on-change="searchExpGroup" style="width: 180px;margin-left: 15px"/>
            <Input v-model.trim="searchNickname" placeholder="成员名" clearable @on-change="searchExpGroup" style="width: 180px;margin-left: 15px"/>
            <Button class="header-btn" type="primary" ghost style="height: 32px;margin-left: 5px;" @click="refreshExpGroup()"><i class="el-icon-refresh-right" /></Button>
        </template>
        <!-- 创建/修改 实验组-->
        <Modal
                v-model="reGroupModal"
                :mask-closable="false"
                width="500"
                :footer-hide="true"
                @on-visible-change="visibleChange"
                :title="groupText">
            <Form ref="formItem" :model="formItem" :rules="formItemRuleValidate" :label-width="80">
                <FormItem label="名称" prop="name">
                    <Input v-model.trim="formItem.name" placeholder="名称"></Input>
                </FormItem>
                <FormItem label="可见范围" prop="visibility">
                    <RadioGroup v-model="formItem.visibility">
                        <Radio label="company">单位</Radio>
                        <Radio label="person">个人</Radio>
                    </RadioGroup>
                </FormItem>
                <FormItem label="描述" prop="description">
                    <Input v-model.trim="formItem.description" type="textarea" :maxlength="200" :autosize="{minRows: 2,maxRows: 5}" placeholder="描述"></Input>
                </FormItem>
                <FormItem>
                    <Button type="primary" @click="formBtn('formItem')" :loading="loading">确定</Button>
                    <Button @click="exGroupHandleReset('formItem')" style="margin-left: 8px">重置</Button>
                </FormItem>
            </Form>
        </Modal>
        <!--生成邀请链接-->
        <Modal
                v-model="modal3"
                :mask-closable="false"
                width="500" :footer-hide="true"
                title="邀请链接">
            <Form :model="teamLink" :label-width="80">
                <FormItem label="链接">
                    <input id='input_url' v-model='teamLink.name' style='opacity: 0;position: absolute;' type="text">
                    <Input type="text" v-model="teamLink.name" disabled></Input>
                    <Button  style="margin-top: 15px" class="add-member" type="primary"
                            @click="copyTeamLink">复制链接</Button>
                </FormItem>
            </Form>
        </Modal>
        <!--实验组的申请列表-->
        <Modal :closable="false" :mask-closable="false" width="800" v-model="applyModal" :title="applyGroupName">
            <div>
                <Table :columns="applyGroupCol" :data="applyList"></Table>
            </div>
        </Modal>
    </MenuPage>
</template>
<script>
    const YXURL_Comper = 'https://130.2.1.33'
    const YXURL_Train = 'http://130.2.1.31'
    import $ from 'jquery'
    import encryption from '@/libs/encryption.js'
    import {getGroupHasUsers,getExperiData,verifyUserName,createUser,delCompanyMember,creatGroup,reGroup,
        delGroup,creatInvaita,checkApply,agreeApply,refuseApply,resetPwd,getPwdBlackList,exportUsers,exportGroups,deleteListUser,deleteGroups,exportGroupsNew} from '@/api/company.js'
    import {modifyCompanyUserInfo,changePassword} from '@/api/user.js'
    import { reportedGroups,getRangeAll } from '@/api/reported-data'
    import {sendToUser} from '@/api/boardcast_new.js'
    import resourcesReportedMixin from '@/mixin/resources-reported-mixin'
    import {
        debounce
    } from '@/libs/utils'
    export default {
        name:'experGround',
        components:{},
        mixins: [resourcesReportedMixin],
        data () {
            let regUsername = /^[0-9A-Za-z_]{5,18}$/;   // 账号是数字 字母 或者下划线的组合
            let regPasswd = /^(?!.*\s)(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[\W_]).{8,16}$/;     // 密码必须包含大小写字母、数字和特殊字符，长度为8—16
            const validateUsername = (rule, value, callback) => {
                if(regUsername.test(value)){
                    callback();
                }else {
                    callback(new Error('请输入长度为5-18位的账号,可以使用数字、字母或者下划线'));
                }
            };
            const validatePass = (rule, value, callback) => {
                if(regPasswd.test(value)){
                    callback();
                }else {
                    callback(new Error('密码必须包含大写字母，小写字母，数字和特殊字符，长度为8-16位'));
                }
            };
            const validateNickname = (rule, value, callback) => {
                if(value.length < 1){
                    callback(new Error('昵称不能为空'));
                }else if(value.length > 32){
                    callback(new Error('昵称长度不能超过32位'));
                }else {
                    callback();
                }
            };
            const validateGroupname = (rule, value, callback)=>{
                if(value.length < 1){
                    callback(new Error('实验组名称不能为空'));
                }else if(value.length > 32){
                    callback(new Error('实验组名称长度不能超过32'));
                }else if(value.indexOf('@') > -1){
                    callback(new Error('实验组名称不能使用@符'));
                }else{
                    callback();
                }
            }
            return {
                userForm:{
                    id:""
                },
                newPassword:{
                    Password:''
                },
                showChangePass:false,
                // 用户信息
                USER_ID:'',
                isRootDesigner:'',
                distributed: false,
                // 页面设置
                fullHeight: document.documentElement.clientHeight,
                fullWidth: document.documentElement.clientWidth,
                setTableHei:'auto',
                // 表格显示
                showGroupData:false,
                showGroupImg:false,
                // 单位
                // 获取所有的课件用户组
                allGroupList:[],
                // 课件用户组数据
                ExperimentalUserGroupList:[],
                groupCol: [
                    {
                        type: 'selection',
                        width: 60,
                        align: 'left'
                    },
                    {
                        title: '实验组名称',
                        key: 'name',
                        tooltip: true,
                        placement:'top-left'
                    },

                    {
                        title: '成员',
                        key: 'userList',
                        filter: (userList) => {
                            return userList.map((user) => user.nickname).join(',');
                        },
                        minWidth: 100,
                        tooltip: true
                    },
                    { title: '所属靶场', key: 'rangeName', minWidth: 50, tooltip: true,show:this.$store.state.common.showDistributed },
                    {
                        type: 'Tag',
                        title: '申请人',
                        key: 'applyCount',
                        on:{
                            click:(data) => {
                                this.showApplyList(data)
                            }
                        },
                        setColor: (applyCount) => {
                            return 'var(--url-color)';
                        },
                        tooltip: true
                    },
                    {
                        title: '可见范围',
                        key: 'visibility',
                        filter: (visible) => {
                            return this.setVisibility(visible).text;
                        },
                        setColor: (visible) => {
                            return this.setVisibility(visible).color;
                        }
                    },
                    {
                        title:'上报状态',
                        key:'reportedStatus',
                        show:() => {
                            return this.distributed
                        },
                        filter:(reportedStatus) => {
                            return reportedStatus == '0'
                                ? '上报失败'
                                : reportedStatus == '1'
                                ? '上报中'
                                : reportedStatus == '2'
                                ? '上报成功'
                                : '未上报'
                        },
                        setColor:(reportedStatus) => {
                            return reportedStatus == '0'
                                ? '#ed4014'
                                : reportedStatus == '1'
                                ? '#ff9900'
                                : reportedStatus == '2'
                                ? '#19be6b'
                                : 'grey'
                        },
                        disabled:(data) => {
                            return !data.reportedMsg
                        },
                        tooltip:true,
                        tooltipKey:'reportedMsg'
                    },
                    {
                        title: '创建者',
                        key: 'creatorName',
                        tooltip: true
                    },
                    {
                        title: '创建时间',
                        key: 'created',
                        tooltip: true
                    },
                    {
                        title: '操作',
                        slot: 'action',
                        width: 240,
                        opList: [
                            {
                                txt: '修改',
                                type:'modify',
                                disabled: this.setIsClick,
                                on:{
                                    click:(data,e) => {
                                        this.madifyGroup(data)
                                    }
                                }
                            },
                            {
                                txt: '邀请',
                                type:'invita',
                                on:{
                                    click:(data,e) => {
                                        this.createdInvitation(data)
                                    }
                                }
                            },
                            {
                                txt: '成员管理',
                                type:'mems',
                                on:{
                                    click:(data,e) => {
                                        this.membersManage(data)
                                    }
                                }
                            },
                            {
                                txt: '删除',
                                tooltip: true,
                                type: 'delete',
                                title: '确定要删除吗？',
                                on:{
                                    click:(data,e) => {
                                        this.delGroup(data)
                                    }
                                },
                                disabled: this.setIsClick
                            }
                        ]
                    }
                ],
                isCanClickReviceAndDelBtn:false,
                experGroupLoading:false,
                expGroupVisibility:'',
                filterExpGroup:'all',
                expGroupCount:0,
                groupPage:1,
                groupPageSize:12,
                expGroupName:'',
                searchExpGroupInput:'',
                searchNickname:'',
                createByMe:false,
                // 创建/修改实验组
                groupText:'',
                isCreate:true,
                reGroupModal:false,
                loading:false,
                formItem:{
                    name:'',
                    visibility:'company',
                    description:'',
                },
                formItemRuleValidate: {
                    name: [
                        { required: true,validator: validateGroupname, trigger: 'change' },
                        { type: 'string',min: 1, max:32,  message: '请选择能见度', trigger: 'change' },
                    ],
                    visibility: [
                        { required: true, message: '请选择能见度 ', trigger: 'change' }
                    ],
                    description:[
                        { max: 200, message: '说明不能超过200个字母', trigger: 'change' },
                    ],
                },
                reGroupId:'',
                // 邀请码
                modal3:false,
                teamLink:{
                    name:'',
                },
                // 处理申请
                applyModal:false,
                applyGroupName:'',
                applyList:[],
                applyGroupCol:[
                    {
                        title:'序号',
                        type:'index',
                        width:60,
                        align:'left',
                    },
                    {
                        title:'用户名',
                        key:'userName',
                        align:'left',
                    },
                    {
                        title:'邀请人',
                        key:'inviterName',
                        align:'left',
                    },
                    {
                        title:'申请状态',
                        key:'status',
                        align:'left',
                    },
                    {
                        title: '操作',
                        key: 'action',
                        align: 'left',
                        render:(h,params)=>{
                            return h('div',[
                                h('a',{
                                    style:{
                                        'display': 'flex',
                                        'justify-content': 'flex-start',
                                        'align-items': 'left',
                                        color:'rgb(82, 56, 144)'
                                    },
                                },[
                                    h('div',{
                                        on:{
                                            click:()=>{
                                                this.agreeApply(params)
                                            }
                                        }
                                    }, [
                                        h('img', {
                                            attrs: {
                                                src: require('../../assets/project/agree-h.png'),
                                            },
                                            style: {
                                                cursor: 'pointer',
                                                'margin-right':'5px',
                                                'vertical-align': 'middle',
                                                width:'22px',
                                                height:'22px',
                                                display:'inline-block',
                                                marginBottom:'4px',
                                            },
                                        }),
                                        h('span',{
                                            style: {
                                                cursor: 'pointer',
                                            },
                                        },'同意')]),
                                    h('div',{
                                        style:{'margin-left':'20px'},
                                        on:{
                                            click:()=>{
                                                this.refuseApply(params.row)
                                            }
                                        }
                                    }, [
                                        h('img', {
                                            attrs: {
                                                src: require('../../assets/project/refuse-h.png'),
                                            },
                                            style: {
                                                cursor: 'pointer',
                                                'margin-right':'5px',
                                                'vertical-align': 'middle',
                                                width:'22px',
                                                height:'22px',
                                                display:'inline-block',
                                                marginBottom:'4px',
                                            },
                                        }),
                                        h('span',{
                                            style: {
                                                cursor: 'pointer',
                                            },
                                        },'拒绝')]),
                                ]),
                            ])
                        }
                    }
                ],
                // 密码黑名单
                pwdBlackList:[],
                // 重置密码img
                // resetImg:require('../../assets/project/resetPwd-h.png'),
                invitaIcon:require('../../assets/project/invita-h.png'),
                memsIcon:require('../../assets/project/mems-h.png'),
                //导入报告
                uploadAction: "/api/identity/company/users/import",
                uploadGroupAction:"/api/identity/experimenterGroups/import",
                uploadHeader: {
                    Authorization:localStorage.token,
                    Accept:'*/*'
                },
                uploadList:[],
                uploaderror:false,
                filename:'',
                selectAllGroup:false,
                selectGroups:[],
                isRetainer:true,
                rangeAllList:[],
                rangeId:'',
                local:true,
                mainRangeflag:true
            }
        },
        created(){
            // 获取用户id
            let November = sessionStorage.getItem('November')
            November = JSON.parse(encryption.SelfUseDecrypt(November))
            this.USER_ID = November.userId
            this.isRootDesigner = November.isRootDesigner
            this.distributed = November.distributed
            this.userName = November.userName
            this.isRetainer = sessionStorage.getItem('isRetainer') === 'true'
            console.log('%c [ this.isRetainer ]', 'font-size:13px; background:pink; color:#bf2c9f;', this.isRetainer)
        },
        mounted(){
            //赋值查询条件
            let queryObj = sessionStorage.getItem('queryObj');
            if(queryObj){
                let params = JSON.parse(queryObj);
                this.groupPage = params.pageIndex;
                this.expGroupVisibility = params.visibility;
                this.expGroupName = params.name;
                this.createByMe = params.created || false;
                sessionStorage.removeItem("queryObj");
            }
            // this.setStyle()
            $('.company-page .ivu-divider-horizontal').css({
                margin:0
            })
            // window.onresize = () => {
            //     this.setStyle()
            // }
//          let getPage = this.$route.query.page?parseInt(this.$route.query.page):1
//          this.groupPage = getPage
            this.queryExperimentalUserGroup()
            this.isRetainer = sessionStorage.getItem('isRetainer') === 'true'
            console.log('%c [ this.isRetainer ]', 'font-size:13px; background:pink; color:#bf2c9f;', this.isRetainer)
            this.queryAllRange()
        },
        computed:{
            distributedRange(){
                return this.$store.state.user.distributedRange
            },
            pageTitle () {
                //当前菜单显示名
                return this.$route.meta.title;
            },
        },
        
        methods:{
            visibleChange(type) {
                if (!type) {
                    this.$refs.formItem.resetFields()
                }
            },
            // 设置高度
            setStyle(){
                window.fullHeight = document.documentElement.clientHeight;
                window.fullWidth = document.documentElement.clientWidth;
                this.fullHeight = window.fullHeight;
                this.fullWidth = window.fullWidth;
                this.setTableHei = this.fullHeight - 197 +'px'
                let num = this.fullHeight - 197
                this.groupPageSize = Math.floor(num / 102)
            },
            // 实验组列表
            queryExperimentalUserGroup:debounce(function(){
                let params = {
                    pageIndex:this.groupPage,
                    pageSize:this.groupPageSize,
                    visibility:this.expGroupVisibility,
                    name:this.expGroupName,
                    order:'desc',
                    sortBy:'created',
                    nickname:this.searchNickname,
                    local:this.local
                }
                if(this.rangeId){
                    params.rangeId = this.rangeId
                }
                if(this.createByMe){
                    params.created = true;
                }
                this.queryObj = JSON.stringify(params);
                if(this.experGroupLoading){ //正在请求，有新的请求
                    this.hasNoExecuteRequest = true;
                    return;
                }
                this.experGroupLoading = true
                getGroupHasUsers(params)
                    .then(async res=>{
                        if(res.data.code == 1){
                            items = res.data.data.items;
                            await this.getUserGroupStatus_mixins(items).then()
                            this.ExperimentalUserGroupList = items
                            this.expGroupCount = res.data.data.total
                            let items = res.data.data.items
                            for(let i=0;i<items.length;i++){
                                items[i].dismissIcon = require('../../assets/project/dismiss-d.png')
                                items[i].modifyIcon = require('../../assets/project/modifys.png')
                                // items[i].invitaIcon = require('../../assets/project/invita-d.png')
                                // items[i].memsIcon = require('../../assets/project/mems-d.png')
                            }
                            if(items.length > 0){
                                this.showGroupData = true
                                this.showGroupImg = false
                            }else{
                                this.showGroupData = false
                                this.showGroupImg = true
                            }
                            this.ExperimentalUserGroupList.forEach(group => {
                                if(this.selectGroups.map(group => group.id).includes(group.id)){
                                    this.$set(group,'_checked',true)
                                }else{
                                    this.$set(group,'_checked',false)
                                }
                            })
                            if(this.ExperimentalUserGroupList.length > 0 && this.ExperimentalUserGroupList.every(group => this.selectGroups.map(group => group.id).includes(group.id))){
                                this.selectAllGroup = true;
                            }else{
                                this.selectAllGroup = false;
                            }
                            this.setMainOrBranch()
                        }else {
                            this.showGroupData = false
                            this.showGroupImg = true
                            this.expGroupCount = 0
                            this.ExperimentalUserGroupList = []
                        }
                        this.experGroupLoading = false
                        if(this.hasNoExecuteRequest){
                            this.expGroupOnChange(1);
                            this.hasNoExecuteRequest = false;
                        }
                    })
                    .catch((err)=>{
                        this.experGroupLoading = false
                        this.showGroupData = false
                        this.showGroupImg = true
                        if(this.hasNoExecuteRequest){
                            this.expGroupOnChange(1);
                            this.hasNoExecuteRequest = false;
                        }
                        console.log(err)
                    })
            },500),
            // 过滤
            expGroupOnChange(val){
                this.groupPage = val
                this.queryExperimentalUserGroup()
            },
            searchExpGroup(val){
                this.groupPage = 1
                val = this.searchExpGroupInput
                this.expGroupName = val
                this.queryExperimentalUserGroup()
            },
            changeExpGroupState(val){
                this.groupPage = 1
                if(val === 'all'){
                    this.expGroupVisibility = ''
                }else {
                    this.expGroupVisibility = val
                }
                this.queryExperimentalUserGroup()
            },
            searchCreatedByMe(val){
                this.groupPage = 1
                this.queryExperimentalUserGroup()
            },
            refreshExpGroup(){
                this.selectGroups = []//清空
                this.groupPage = 1
                this.filterExpGroup = 'all'
                this.rangeId = ''
                this.expGroupVisibility = ''
                this.expGroupName = ''
                this.searchExpGroupInput = ''
                this.searchNickname = ''
                this.createByMe = false
                this.queryExperimentalUserGroup()
            },
            isCanClick(creator){
                if(this.isRootDesigner || this.USER_ID === creator){
                    return false
                }else {
                    return true
                }
            },
            // 创建实验组
            creatGroupBtn(){
                this.isCreate = true
                this.reGroupModal = true
                this.groupText = '创建实验组'
                this.formItem.name = ''
                this.formItem.visibility = 'company'
                this.formItem.description = ''
            },
            // 修改实验组
            madifyGroup(row){
                this.isCreate = false
                this.reGroupModal = true
                this.groupText = '修改实验组'
                this.reGroupId = row.id
                this.formItem.name = row.name
                this.formItem.visibility = row.visibility
                this.formItem.description = row.description
            },
            // 创建/修改
            formBtn(name){
                if(this.isCreate){
                    this.exGroupHandleSubmit(name)
                }else {
                    this.reGroupSubmit(name)
                }
            },
            exGroupHandleSubmit(name){  // 创建
                this.$refs[name].validate((valid) => {
                    if (valid){
                        this.loading = true
                        creatGroup(this.formItem)
                            .then(res=>{
                                if(res.data.code == 1){
                                    this.$Message.success('创建成功！')
                                    this.reGroupModal = false
                                    //this.queryExperimentalUserGroup()
                                    this.refreshExpGroup()
                                }else {
                                    this.$Message.error(res.data.message)
                                }
                                this.loading = false
                            })
                            .catch(err=>{
                                this.loading = false
                                console.log(err)
                                this.$Message.error('服务器连接失败！')
                            })
                    } else {
                        this.$Message.error('请完善信息！');
                    }
                })
            },
            reGroupSubmit(name){
                this.$refs[name].validate((valid) => {
                    if (valid){
                        this.loading = true
                        reGroup(this.reGroupId,this.formItem)
                            .then(res=>{
                                if(res.data.code == 1){
                                    this.$Message.success('修改成功!')
                                    this.reGroupModal = false
                                    this.queryExperimentalUserGroup()
                                }else {
                                    this.$Message.error(res.data.message)
                                }
                                this.loading = false
                            })
                            .catch(err=>{
                                this.loading = false
                                console.log(err)
                            })
                    } else {
                        this.$Message.error('请完善信息！');
                    }
                })
            },
            exGroupHandleReset(name){
                this.$refs[name].resetFields();
            },
            // 解散
            delGroup(params){
                delGroup(params.id)
                    .then(res=>{
                        if(res.data.code == 1){
                            this.$Message.success({
                                content:'删除成功！',
                                duration:3,
                            })
                            this.checkSingleGroup(false,params);
                            this.groupPage = (this.ExperimentalUserGroupList.length == 1 && this.groupPage > 1) ? this.groupPage - 1 : this.groupPage;
                            this.queryExperimentalUserGroup()
                            this.distributed && this.$refs.selectTable.closeItem(params)
                        }else {
                            this.$Message.error('删除失败！')
                        }
                    })
                    .catch(err=>{
                        console.log(err)
                    })
            },
            // 成员管理
            membersManage(row){
                sessionStorage.setItem('queryObj',this.queryObj);
                this.$router.push({
                    name: 'creatGroup',
                    query:{
                        id:row.id,
                        name:row.name,
                        page:this.groupPage,
                        creator:row.creator
                    }
                })
            },
            // 创建邀请
            createdInvitation(params){
                let groupId = params.id
                let formData = {}
                this.modal3 = true
                creatInvaita(groupId,formData)
                    .then(res=>{
                        if(res.data.code == 1){
                            let data = res.data.data;
                            this.teamLink.name = `expGroupId=${data.experimenterGroupId}&token=${data.token}`
                        }else {
                            this.$Message.error('创建课件用户组分享码失败！')
                        }
                    })
                    .catch(err=>{
                        console.log(err)
                        this.$Message.error('服务器连接失败！')
                    })
            },
            // 点击复制链接
            copyTeamLink() {
                var input = $('#input_url');
                input.select();
                document.execCommand("Copy");
                this.$Message.success({
                    content:"复制成功",
                    duration:3,
                });
                this.modal3 = false;
            },
            // 查看申请人
            showApplyList(row){
                if(row.applyCount>0){
                    this.applyGroupName = row.name
                    this.applyList = []
                    this.applyModal = true
                    this.checkApplyData(row.id)
                }
            },
            checkApplyData(id){
                checkApply(id)
                    .then(res=>{
                        if(res.data.code === 1){
                            console.log(res)
                            this.applyList = res.data.data
                        }
                    })
                    .catch(err=>{
                        console.log(err)
                    })
            },
            closeDistribution(){
                this.applyModal = false
            },
            // 同意申请
            agreeApply(params){
                let json = {
                    applyId:params.row.id,
                    groupId:params.row.experimenterGroupId,
                    data:{}
                }
                agreeApply(json)
                    .then(res=>{
                        if(res.data.code == 1){
                            this.applyModal = false
                            this.queryExperimentalUserGroup()
                            this.$Message.success({
                                content: `已同意${res.data.data.userName}加入课件用户组${this.applyGroupName}`,
                                duration: 3,
                            });
                            this.sendToUser(params.row,'agree');
                        }
                    })
                    .catch(err=>{
                        console.log(err)
                    })
            },
            // 拒绝申请
            refuseApply(row){
                let params = {
                    groupId:row.experimenterGroupId,
                    applyId:row.id
                }
                refuseApply(params)
                    .then(res=>{
                        if(res.data.code == 1){
                            this.applyModal = false
                            this.queryExperimentalUserGroup()
                            this.$Message.info({
                                content:'已拒绝加入',
                                duration:3
                            })
                            this.sendToUser(row,'refuse');
                        }
                    })
                    .catch(err=>{
                        console.log(err)
                    })
            },
            handleGroupIndex(key){
                return (this.groupPage-1)*this.groupPageSize + key + 1
            },
            // 设置可见范围
            setVisibility(val){
                let obj = {}
                let text = ''
                let color = ''
                if(val === 'company'){
                    text = '单位'
                    color = '#32CD32'
                }else if(val === 'person'){
                    text = '个人'
                    color = '#FFA500'
                }
                obj.text = text
                obj.color = color
                return obj
            },
            handleApplyStyle(val){
                if(val > 0){
                    return {
                        height:'18px',
                        'line-height':'18px',
                        'text-align':'center',
                        'background-color':'rgb(47, 112, 255)',
                        color:'#fff',
                        'border-radius': '7px',
                        'cursor': 'pointer',
                        padding:'0 10px'
                    }
                }
            },
            // 是否可以删除
            setIsClick(item){
                if((item.creator !== this.USER_ID && !this.isRootDesigner)){
                    return true //{'pointer-events':'none'}
                }
            },
            setImgSrc(item){
                if(item.creator !== this.USER_ID && !this.isRootDesigner){
                    return require('../../assets/project/modifys.png')
                }else{
                    return require('../../assets/project/modifys-h.png')
                }
            },
            setDelImgSrc(item){
                if((item.creator !== this.USER_ID && !this.isRootDesigner) || item.role === 'leader'){
                    return require('../../assets/project/delNote-d.png')
                }else{
                    return require('../../assets/project/delNote-h.png')
                }
            },
            //导入用户（liqing-2020-10-20）
            handleFormatError(){
                this.uploadList = [];
                this.$Message.warning('文件格式错误');
            },
            handleBeforeUpload(file){
                this.uploadList = this.$refs.upload.fileList;
                return true;
            },
            handleProgress(event, file, fileList){

            },
            getImageUrl(res){
                if(res.code == 1){
                    if (res.data && res.data.failedList && res.data.failedList.length) {
                        let { failedTotal, failedList = [] } = res.data
                        let errorMessageList = []
                        failedList.forEach(item => {
                            if (!errorMessageList.includes(item.message)) {
                                errorMessageList.push(item.message)
                            }
                        })
                        if (errorMessageList.length === 0) {
                            this.$Message.info('导入成功');
                            return
                        } else {
                            this.$Message.warning(`操作成功，但有${failedTotal}支队伍导入失败，失败原因: ${errorMessageList[0]}`)
                            // errorMessageList.forEach(item => this.$Message.warning(item))
                        }
                    } else {
                        this.$Message.info('导入成功');
                    }
                    this.queryExperimentalUserGroup();
                }else{
                    this.$Message.warning(res.message);
                }
                this.uploadList = [];
            },
            isDdeleteGroups(){
                let ids = this.selectGroups.map(user => user.id).join(',');
                if(ids.length === 0){
                    this.$Message.error('请选择需要删除的实验组！')
                    return
                }
            },
            //批量删除实验组
            deleteGroups(){
                let deleteGroupsData = this.selectGroups.filter(group => {
                    return !(group.creator !== this.USER_ID && !this.isRootDesigner)
                })
                if(deleteGroupsData.length == 0){
                    this.$Message.success({
                        content:'没有可以删除的实验组！',
                        duration:3,
                    })
                    this.selectGroups = []
                    this.queryExperimentalUserGroup()
                    return;
                }
                let ids = deleteGroupsData.map(group => group.id).join(',');
                deleteGroups(ids).then((res) =>{
                    if(res.data.code == 1){
                            this.selectGroups = []
                            this.$Message.success({
                                content:'删除成功！',
                                duration:3,
                            })
                            this.groupPage = (this.ExperimentalUserGroupList.length == deleteGroupsData.length && this.groupPage > 1) ? this.groupPage - 1 : this.groupPage;
                            this.queryExperimentalUserGroup()
                        }else {
                            this.$Message.error('删除失败！')
                        }
                })
            },
            exportGroups(){
                let ids = this.selectGroups.map(group => group.id);
                if(ids.length == 0){
                    this.$Message.warning('请选择实验组');
                    return
                }
                exportGroupsNew({ids}).then(data => {
                    if(!data.code){
                        const downloadElement = document.createElement("a");
                        const href = window.URL.createObjectURL(data.data);
                        downloadElement.href = href;
                        downloadElement.download = '实验组.xlsx';
                        document.body.appendChild(downloadElement);
                        downloadElement.click();
                        document.body.removeChild(downloadElement); // 下载完成移除元素
                        window.URL.revokeObjectURL(href); // 释放掉blob对象
                        this.selectGroups = [];
                        this.handleCheckAllGroup(false);
                    }else{
                        this.$Message.error('导出用户失败');
                    }
                }).catch(error => {
                    this.$Message.error('导出用户失败!');
                })
            },
            handleCheckAllGroup(e){
                this.selectAllGroup = e;
                this.ExperimentalUserGroupList.forEach(group => {
                    this.checkSingleGroup(e,group);
                })
            },
            checkSingleGroup(e,group){
                if(e && !this.selectGroups.map(group => group.id).includes(group.id)){
                    this.selectGroups.push(group);
                }else if(!e && this.selectGroups.map(group => group.id).includes(group.id)){
                    let index = this.selectGroups.findIndex(item => group.id == item.id);
                    this.selectGroups.splice(index,1);
                }
                this.$set(group,'_checked',e);
                if(this.ExperimentalUserGroupList.length > 0 && this.ExperimentalUserGroupList.every(group => group._checked === true)){
                    this.selectAllGroup = true;
                }else{
                    this.selectAllGroup = false;
                }
            },
            //发送公告
            sendToUser(row,type){
                let params = {
                    "content": type == "agree" ? `[${this.userName}]已同意你加入实验组[${this.applyGroupName}]`: `[${this.userName}]已拒绝你加入实验组[${this.applyGroupName}]`,
                    "id": "",
                    "status": 0,
                    "title": "",
                    "type": 1,
                    "users": [
                        {
                        "userIds": [row.userId]
                        }
                    ]
                }
                sendToUser(params).then(data => {
                    if(data.code==1){
                        //this.$Message.info('发送成功');
                    }else{
                        //this.$Message.error(data.message);
                        setTimeout(() => {
                            this.sendToUser(row,type);
                        },2000)
                    }
                }).catch(error => {
                    console.log(error);
                    //this.$Message.error("公告发送失败");
                })
            },
            // 上报实验组
            reportedGroups() {
                let ids = this.selectGroups.map(group => group.id);
                if(ids.length == 0){
                    this.$Message.warning('请选择实验组');
                    return
                }
                reportedGroups(ids).then(({ code, message }) => {
                    if (code !== 1) {
                        this.$Message.warning(message)
                        return
                    }
                    this.$Message.info('上报实验组成功')
                    this.queryExperimentalUserGroup()
                    this.selectGroups = [];
                    this.handleCheckAllGroup(false);
                }).catch(() => {
                    this.$Message.error('上报实验组异常')
                })
            },
            searchItem(val){
               let res =  this.rangeAllList.find(item=>{
                   return item.id==val
                })
                if(res&&res.self!=0){
                    this.local =false
                    this.queryExperimentalUserGroup();
                }else{
                    this.local = true
                    this.queryExperimentalUserGroup();
                }
                
            },
            setMainOrBranch(){
                let res =  this.rangeAllList.find(item=>{
                   return item.id==this.rangeId
                })
                if(res&&res.self!=0){
                    this.mainRangeflag = false // 分靶场
                }else{
                    this.mainRangeflag = true // 主靶场
                }
            },
             //查询所有分靶场信息
            queryAllRange() {
                getRangeAll().then(res => {
                    if (res.code === 1) {
                    this.rangeAllList = res.data.items
                    res.data.items.forEach(item=>{
                        if(item.level== 'LOCAL'){
                            this.rangeId = item.id
                        }
                    })
                    }
                })
            },
        }
    }
</script>
<style scoped>
    .downloadUrl{
        color:#a5a5c6;
    }
    .downloadUrl:hover{
        /* color:rgb(91,54,194); */
    }
</style>
